package com.scraper.articles.web.controller;

import com.scraper.articles.web.model.news.NewsItem;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {

    @RequestMapping(value = {"/"})
    public String chart() throws IOException, ParseException {
        return "app/news";
    }

    @RequestMapping(value = {"/list/{searchTerm}"})
    public
    @ResponseBody
    List<NewsItem> newsList(@PathVariable String searchTerm) throws IOException, ParseException {
        List<NewsItem> newsDataList = new ArrayList<>();
        URL resource = getClass().getResource("/data/news/" + searchTerm.toLowerCase() + ".csv");
        Reader in = new FileReader(resource.getFile());
        Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader("Date", "Title").parse(in);
        int i = 0;
        for (CSVRecord record : records) {
            String date = record.get("Date");
            String title = record.get("Title");
            if (i != 0) {
                newsDataList.add(new NewsItem(date, title));
            }
            i++;
        }
        return newsDataList;
    }
}
